package com.jzo2o.health.listener;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.JsonUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.health.constant.RabbitConstants;
import com.jzo2o.health.constant.TradeConstants;
import com.jzo2o.health.enums.OrderStatusEnum;
import com.jzo2o.health.model.domain.Orders;
import com.jzo2o.health.model.dto.request.OrdersCancelReqDTO;
import com.jzo2o.health.properties.TradeProperties;
import com.jzo2o.health.service.IOrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 监听mq消息，接收支付结果
 *
 * @author itcast
 **/
@Slf4j
@Component
public class TradeStatusListener {
    @Autowired
    private TradeProperties tradeProperties;
    @Autowired
    private IOrdersService ordersService;

    /**
     * 更新支付结果
     * 支付成功
     *
     * @param msg 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = TradeConstants.MQ_TRADE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS
    ))
    public void listenTradeUpdatePayStatusMsg(String msg) {
        //1. 将消息JSON字符串转为消息对象列表
        JSONArray jsonArray = JSONUtil.parseArray(msg);
        List<TradeStatusMsg> tradeStatusMsgs = JsonUtils.toList(jsonArray, TradeStatusMsg.class);
        if (ObjectUtils.isEmpty(tradeStatusMsgs)){
            return;
        }
        log.info("收到订单状态更新消息:{}", tradeStatusMsgs);

        //2. 遍历消息对象列表筛选归属于订单系统的数据并执行更新订单操作
        tradeStatusMsgs.stream().filter(x->x.getProductAppId().equals(tradeProperties.getProductAppId())
                        && x.getStatusCode().equals(TradingStateEnum.YJS.getCode()))
                .forEach(y->ordersService.payResult(y.getProductOrderNo()));


    }



    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitConstants.OVER_TIME_QUEUE),
            exchange = @Exchange(name = RabbitConstants.OVER_TIME_EXCHANG, delayed = "true"),
            key = RabbitConstants.OVER_TIME_ROUTING_KEY
    ))
    public void listenCancelPayStatusByOverTimeMsg(String idStr) {
        log.info("接收到订单id: {}", idStr);
        //判断订单是否存在
        Long id = Long.parseLong(idStr);
        Orders orders = ordersService.getById(id);
        if (ObjectUtils.isEmpty(orders)) {
            log.info("订单不存在");
            return;
        }
        OrdersCancelReqDTO ordersCancelReqDTO = new OrdersCancelReqDTO();
        ordersCancelReqDTO.setId(id);
        ordersCancelReqDTO.setCancelReason("订单超时未支付");
        //更新订单状态为取消
        ordersService.cancelNoPay(ordersCancelReqDTO,true);

    }

}


